package com.live.proxy.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.proxy.BaseActivity;
import com.live.proxy.R;
import com.live.proxy.model.AppUserModel;
import com.live.proxy.model.IndustryModel;
import com.live.proxy.model.ThaliModel;
import com.live.proxy.model.UserModel;
import com.live.proxy.sql.UserDatabase;
import com.live.proxy.tool.GetUtil;
import com.live.proxy.tool.IndustryArrayAdapter;
import com.live.proxy.tool.OkHttpUtils;
import com.live.proxy.tool.StatusBarUtils;
import com.live.proxy.tool.ThaliArrayAdapter;
import com.live.proxy.view.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class UserManageActivity extends BaseActivity {
    ImageButton user_manage_back;
    TextView user_manage_add;
    RecyclerView user_manage_recyclerview;

    UserDatabase userDb;
    UserModel userModel;
    List<AppUserModel> list;
    List<ThaliModel> thaliList = new ArrayList<>();
    List<IndustryModel> industryList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_manage);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        user_manage_back = findViewById(R.id.user_manage_back);
        user_manage_add = findViewById(R.id.user_manage_add);
        user_manage_recyclerview = findViewById(R.id.user_manage_recyclerview);

        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        user_manage_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        user_manage_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_user_add();
            }
        });
        init();
    }
    //加载套餐
    public void reloadThali(){
        try {
            JSONObject appJson = GetUtil.getAppInfo(getApplicationContext());
            getAccount(GetUtil.getThaliIndustryList(),appJson.toString(),userModel.getToken(),3);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //加载用户列表
    public void init(){
        try {
            JSONObject appJson = GetUtil.getAppInfo(getApplicationContext());
            getAccount(GetUtil.getUserList(),appJson.toString(),userModel.getToken(),1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private MyAdapter adapter;

    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_appuser, parent, false));
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyAdapter.MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;

            mholder.item_appuser_user_nickname.setText(list.get(position).getUserNickname());
            mholder.item_appuser_user_name.setText(list.get(position).getUserName());
            mholder.item_appuser_version_name.setText(list.get(position).getLoginVersionName());
            mholder.item_appuser_thali_time.setText(list.get(position).getThaliStarttime()+" - "+list.get(position).getThaliEndtime());
            if(list.get(position).getQaStatus() == 1){
                mholder.item_appuser_qa_status.setText("已订购，结束至："+list.get(position).getQaEndtime());
            }else{
                mholder.item_appuser_qa_status.setText("未订购");
            }
            if(list.get(position).getTrainStatus() == 1){
                mholder.item_appuser_train_status.setText("已订购，结束至："+list.get(position).getTrainEndtime());
            }else{
                mholder.item_appuser_train_status.setText("未订购");
            }
            mholder.item_appuser_create_time.setText(list.get(position).getCreateTime());

            mholder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //选择：套餐续费、AI问答加购、AI训练加购
                    dialog_user_operate(position);
                }
            });
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_appuser_user_nickname;
            TextView item_appuser_user_name;
            TextView item_appuser_version_name;
            TextView item_appuser_thali_time;
            TextView item_appuser_qa_status;
            TextView item_appuser_train_status;
            TextView item_appuser_create_time;

            public MyViewHolder(View itemView) {
                super(itemView);
                item_appuser_user_nickname = itemView.findViewById(R.id.item_appuser_user_nickname);
                item_appuser_user_name = itemView.findViewById(R.id.item_appuser_user_name);
                item_appuser_version_name = itemView.findViewById(R.id.item_appuser_version_name);
                item_appuser_thali_time = itemView.findViewById(R.id.item_appuser_thali_time);
                item_appuser_qa_status = itemView.findViewById(R.id.item_appuser_qa_status);
                item_appuser_train_status = itemView.findViewById(R.id.item_appuser_train_status);
                item_appuser_create_time = itemView.findViewById(R.id.item_appuser_create_time);
            }
        }
    }
    //选择：套餐续费、AI问答加购、AI训练加购
    public void dialog_user_operate(int position){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();//这里要添加window  这才是重点
        window.setContentView(R.layout.dialog_user_operate);
        final TextView dialog_user_operate_reuservip = window.findViewById(R.id.dialog_user_operate_reuservip);
        final TextView dialog_user_operate_reuseraiqa = window.findViewById(R.id.dialog_user_operate_reuseraiqa);
        final TextView dialog_user_operate_reuseraitrain = window.findViewById(R.id.dialog_user_operate_reuseraitrain);

        dialog_user_operate_reuservip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialog_user_revip(position);
            }
        });
        dialog_user_operate_reuseraiqa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                try {
                    JSONObject json = new JSONObject();
                    json.put("uuid",list.get(position).getUuid());
                    getAccount(GetUtil.getUserAiQa(),json.toString(),userModel.getToken(),4);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        dialog_user_operate_reuseraitrain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                try {
                    JSONObject json = new JSONObject();
                    json.put("uuid",list.get(position).getUuid());
                    getAccount(GetUtil.getUserAiTrain(),json.toString(),userModel.getToken(),4);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
    //新增用户
    public void dialog_user_add(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_user_add);

        final AppCompatSpinner dialog_adduser_thali = window.findViewById(R.id.dialog_adduser_thali);
        final AppCompatSpinner dialog_adduser_industry = window.findViewById(R.id.dialog_adduser_industry);
        final EditText dialog_adduser_nickname = window.findViewById(R.id.dialog_adduser_nickname);
        final EditText dialog_adduser_account = window.findViewById(R.id.dialog_adduser_account);
        final EditText dialog_adduser_password = window.findViewById(R.id.dialog_adduser_password);
        final TextView dialog_adduser_title = window.findViewById(R.id.dialog_adduser_title);
        final TextView dialog_adduser_no = window.findViewById(R.id.dialog_adduser_no);
        final TextView dialog_adduser_ok = window.findViewById(R.id.dialog_adduser_ok);

        final int[] selectThaliPositon = {-1};
        final int[] selectIndustryPositon = {-1};
        //套餐列表
        ThaliArrayAdapter thaliAdapter = new ThaliArrayAdapter(getApplicationContext(), thaliList,15);
        dialog_adduser_thali.setAdapter(thaliAdapter);
        dialog_adduser_thali.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //获取Spinner控件的适配器
                selectThaliPositon[0] = position;
                dialog_adduser_title.setText("已选择："+thaliList.get(position).getThaliName());
                if(adapter != null){
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //没有选中时的处理
            }
        });
        //行业列表
        IndustryArrayAdapter industryAdapter = new IndustryArrayAdapter(getApplicationContext(), industryList,15);
        dialog_adduser_industry.setAdapter(industryAdapter);
        dialog_adduser_industry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //获取Spinner控件的适配器
                selectIndustryPositon[0] = position;
                dialog_adduser_title.setText("已选择："+industryList.get(position).getIndustryName());
                if(adapter != null){
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //没有选中时的处理
            }
        });
        dialog_adduser_title.setText("剩余["+userModel.getInteYue()+"]积分");

        dialog_adduser_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_adduser_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nickname = dialog_adduser_nickname.getText().toString();
                String account = dialog_adduser_account.getText().toString();
                String password = dialog_adduser_password.getText().toString();
                if(selectIndustryPositon[0] == -1){
                    ToastUtils.Setinfo(getApplicationContext(),"请选择行业！",2);
                    return;
                }
                if(selectThaliPositon[0] == -1){
                    ToastUtils.Setinfo(getApplicationContext(),"请选择套餐！",2);
                    return;
                }
                if(nickname.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入昵称！",2);
                    return;
                }
                if(account.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入账号！",2);
                    return;
                }
                if(password.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入密码！",2);
                    return;
                }
                int intenum = thaliList.get(selectThaliPositon[0]).getVipAmount();
                if(intenum > userModel.getInteYue()){
                    dialog_adduser_title.setText("套餐消耗["+intenum+"]积分，剩余["+userModel.getInteYue()+"]积分不足！");
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("industry_id",industryList.get(selectIndustryPositon[0]).getIndustryId());
                    json.put("thali_id",thaliList.get(selectThaliPositon[0]).getThaliId());
                    json.put("user_nickname",nickname);
                    json.put("user_name",account);
                    json.put("user_password",password);
                    getAccount(GetUtil.addUser(),json.toString(),userModel.getToken(),2);
                }catch (Exception e){
                    e.printStackTrace();
                }
                String proxyMsg = "用户昵称："+nickname+" \n账户："+account+" \n密码："+password;
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("Label", proxyMsg);
                cm.setPrimaryClip(mClipData);
                ToastUtils.Setinfo(getApplicationContext(),"信息已复制到剪贴板",1);
                dialog.dismiss();
            }
        });
    }
    //套餐续费
    public void dialog_user_revip(int position){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_user_revip);

        final AppCompatSpinner dialog_user_revip_thali = window.findViewById(R.id.dialog_user_revip_thali);
        final TextView dialog_user_revip_title = window.findViewById(R.id.dialog_user_revip_title);
        final TextView dialog_user_revip_no = window.findViewById(R.id.dialog_user_revip_no);
        final TextView dialog_user_revip_ok = window.findViewById(R.id.dialog_user_revip_ok);

        final int[] selectThaliPositon = {-1};
        //套餐列表
        ThaliArrayAdapter thaliAdapter = new ThaliArrayAdapter(getApplicationContext(), thaliList,15);
        dialog_user_revip_thali.setAdapter(thaliAdapter);
        dialog_user_revip_thali.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //获取Spinner控件的适配器
                selectThaliPositon[0] = position;
                dialog_user_revip_title.setText("已选择："+thaliList.get(position).getThaliName());
                if(adapter != null){
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //没有选中时的处理
            }
        });
        dialog_user_revip_title.setText("注意，\n 当前剩余["+userModel.getInteYue()+"]积分");

        dialog_user_revip_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_user_revip_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(selectThaliPositon[0] == -1){
                    ToastUtils.Setinfo(getApplicationContext(),"请选择套餐！",2);
                    return;
                }
                int intenum = thaliList.get(selectThaliPositon[0]).getVipAmount();
                if(intenum > userModel.getInteYue()){
                    dialog_user_revip_title.setText("套餐消耗["+intenum+"]积分，剩余["+userModel.getInteYue()+"]积分不足！");
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("uuid",list.get(position).getUuid());
                    json.put("thali_id",thaliList.get(selectThaliPositon[0]).getThaliId());
                    getAccount(GetUtil.reUserVip(),json.toString(),userModel.getToken(),3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    //AI问答加购、AI训练加购
    public void dialog_user_reai(String message,int uuid,int residue_inte,String type){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_user_reai);

        final TextView diaglog_user_reai_neirong = window.findViewById(R.id.diaglog_user_reai_neirong);
        final TextView diaglog_user_reai_myinte = window.findViewById(R.id.diaglog_user_reai_myinte);
        final TextView diaglog_user_reai_no = window.findViewById(R.id.diaglog_user_reai_no);
        final TextView diaglog_user_reai_ok = window.findViewById(R.id.diaglog_user_reai_ok);
        diaglog_user_reai_myinte.setText("我的积分："+userModel.getInteYue());
        diaglog_user_reai_neirong.setText(message);

        diaglog_user_reai_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        diaglog_user_reai_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(residue_inte > userModel.getInteYue()){
                    ToastUtils.Setinfo(getApplicationContext(),"积分不足",2);
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("uuid",uuid);
                    if(type.equals("AiQa")){
                        getAccount(GetUtil.reUserAiQa(),json.toString(),userModel.getToken(),2);
                    }else if(type.equals("AiTrain")){
                        getAccount(GetUtil.reUserAiTrain(),json.toString(),userModel.getToken(),2);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }

    public static int REQUEST_STATUS = 0;
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastUtils.Setinfo(getApplicationContext(),msg.obj.toString(),2);
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            switch (REQUEST_STATUS){
                                case 1://获取列表
                                    if(list != null){
                                        list.clear();
                                    }else{
                                        list = new ArrayList<>();
                                    }
                                    JSONArray dataJson = json.getJSONArray("data");
                                    for (int i = 0 ; i < dataJson.length() ;i++){
                                        JSONObject inteJson = dataJson.getJSONObject(i);
                                        AppUserModel model = new AppUserModel();
                                        model.setUuid(inteJson.getInt("uuid"));
                                        model.setUserNickname(inteJson.getString("user_nickname"));
                                        model.setUserName(inteJson.getString("user_name"));
                                        model.setQaStatus(inteJson.getInt("qa_status"));
                                        model.setQaEndtime(inteJson.getString("qa_endtime"));
                                        model.setTrainStatus(inteJson.getInt("train_status"));
                                        model.setTrainEndtime(inteJson.getString("train_endtime"));
                                        model.setThaliStarttime(inteJson.getString("thali_starttime"));
                                        model.setThaliEndtime(inteJson.getString("thali_endtime"));
                                        model.setLoginVersionName(inteJson.getString("login_versionName"));
                                        model.setCreateTime(inteJson.getString("create_time"));
                                        list.add(model);
                                    }
                                    adapter = new MyAdapter();
                                    user_manage_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                                    user_manage_recyclerview.setAdapter(adapter);

                                    if(thaliList.size() == 0){
                                        reloadThali();
                                    }
                                    break;
                                case 2://新增用户、套餐续费、AI问答加购、AI训练加购
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    userModel.setInteYue(json.getInt("data"));
                                    userDb.updateInteYue(json.getInt("data"));
                                    init();
                                    break;
                                case 3://获取套餐行业列表
                                    JSONObject valueJson = json.getJSONObject("data");
                                    JSONArray thalisArray = valueJson.getJSONArray("thalis");
                                    for (int i = 0 ; i < thalisArray.length() ;i++){
                                        JSONObject thalisJson = thalisArray.getJSONObject(i);
                                        ThaliModel model = new ThaliModel();
                                        model.setThaliId(thalisJson.getInt("thali_id"));
                                        model.setThaliName(thalisJson.getString("thali_name"));
                                        model.setVipAmount(thalisJson.getInt("vip_amount"));
                                        model.setQaAmount(thalisJson.getInt("qa_amount"));
                                        model.setTrainAmount(thalisJson.getInt("train_amount"));
                                        thaliList.add(model);
                                    }
                                    JSONArray industrysArray = valueJson.getJSONArray("industrys");
                                    for (int i = 0 ; i < industrysArray.length() ;i++){
                                        JSONObject industryJson = industrysArray.getJSONObject(i);
                                        IndustryModel model = new IndustryModel();
                                        model.setIndustryId(industryJson.getInt("industry_id"));
                                        model.setIndustryName(industryJson.getString("industry_name"));
                                        industryList.add(model);
                                    }
                                    break;
                                case 4://获取AI加购信息
                                    JSONObject aiJson = json.getJSONObject("data");
                                    int residue_inte = aiJson.getInt("residue_inte");
                                    int uuid = aiJson.getInt("uuid");
                                    String remsg = aiJson.getString("msg");
                                    String type = aiJson.getString("type");
                                    //加载信息
                                    dialog_user_reai(remsg,uuid,residue_inte,type);
                                    break;
                            }
                        }else{
                            ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),2);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr,String token,int STATUS){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                REQUEST_STATUS = STATUS;
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
}